package com.yj.agent.service;

import cn.com.yj.common.enums.Status;
import cn.com.yj.common.param.out.ServiceResp;
import cn.com.yj.common.repository.BaseRepository;
import com.github.pagehelper.PageHelper;
import com.jcraft.jsch.HASH;
import com.yj.agent.bean.TAgentUserBean;
import com.yj.agent.bean.TOrgUserModel;
import com.yj.agent.bean.TWithDrawBean;
import com.yj.agent.evt.*;
import com.yj.agent.mapper.AgentUserMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class TAgentUserService {

    @Autowired
    private AgentUserMapper agentUserMapper;
    @Autowired
    private BaseRepository baseRepository;
    @Autowired
    private SysnService sysnService;

    public int subCount(QueryAgentUserEvt evt) {
        return agentUserMapper.querySubCount(evt);
    }

    public List<TAgentUserBean> subQuery(QueryAgentUserEvt evt) {
        if (evt.getQueryPage() != null && evt.getQuerySize() != null) {
            PageHelper.startPage(evt.getQueryPage(), evt.getQuerySize(), false, false);
        }
        return agentUserMapper.querySubByParam(evt);
    }

    public TAgentUserBean queryDetail(QueryAgentUserEvt evt) {
        return agentUserMapper.queryDetail(evt);
    }

    public TAgentUserBean queryByUserNo(QueryAgentUserEvt evt) {
        return agentUserMapper.queryByUserNo(evt);
    }


    public int count(QueryAgentUserEvt evt) {
        return agentUserMapper.queryCount(evt);
    }

    public List<TAgentUserBean> query(QueryAgentUserEvt evt) {
        if (evt.getQueryPage() != null && evt.getQuerySize() != null) {
            PageHelper.startPage(evt.getQueryPage(), evt.getQuerySize(), false, false);
        }
        return agentUserMapper.queryByParam(evt);
    }

    public ServiceResp add(AddAgentUserEvt evt) throws Exception {
        // 判断用户是否存在
        QueryAgentUserEvt queryAgentUserEvt = new QueryAgentUserEvt();
        queryAgentUserEvt.setAccountEq(evt.getAccount());
        List<TAgentUserBean> list = query(queryAgentUserEvt);
        if (list != null && list.size() > 0) return new ServiceResp().error("用户已存在");
        TAgentUserBean parentBean = agentUserMapper.queryByGameId(evt.getParentGameId());
        if (parentBean == null || parentBean.getAgentLevel() == null || parentBean.getAgentLevel() == 3) {
            return new ServiceResp().error("分享账号不是代理商，本条记录不保存");
        }
        TAgentUserBean bean = new TAgentUserBean();
        BeanUtils.copyProperties(evt, bean);
        bean.setUserNo(StringUtils.replace(UUID.randomUUID().toString(), "-", ""));
        bean.setAgentTime(new Date());
        // 同步用户,确定用户是否存在
        TOrgUserModel tOrgUserModel =
                sysnService.getUserInfo(evt.getAccount());
        if (tOrgUserModel == null) return new ServiceResp().error("" +
                "无法同步到用户信息,请确认账号是否存在.");
        bean.setGameId(tOrgUserModel.getUserID());
        bean.setParentGameId(StringUtils.isBlank(bean.getParentGameId()) ? "-1" : bean.getParentGameId());
        bean.setRegisterTime(tOrgUserModel.getRegisterDate());
        bean.setUserName(tOrgUserModel.getNickName());
        bean.setProfitTotal(0L);
        bean.setProfitUsedTotal(0L);
        bean.setDeTotal(0L);
        bean.setCreateTime(new Date());
        bean.setStatus(Status.E.name());
        bean = baseRepository.save(bean);
        return new ServiceResp().success(bean);
    }

    public ServiceResp cancleBind(EditAgentUserEvt evt) {
        // 查询记录是否存在
        QueryAgentUserEvt queryEvt = new QueryAgentUserEvt();
        queryEvt.setId(evt.getId());
        List<TAgentUserBean> lst = query(queryEvt);
        if (lst == null || lst.size() == 0) return new ServiceResp().error("记录不存在");
        TAgentUserBean item = lst.get(0);
        // 类型改为玩家
        item.setAgentLevel(3);
        // 父ID设置为空
        baseRepository.save(item);
        return new ServiceResp().success("");
    }

    public ServiceResp edit(EditAgentUserEvt evt) {
        // 查询记录是否存在
        QueryAgentUserEvt queryEvt = new QueryAgentUserEvt();
        queryEvt.setId(evt.getId());
        List<TAgentUserBean> lst = query(queryEvt);
        if (lst == null || lst.size() == 0) return new ServiceResp().error("记录不存在，无法编辑");
        TAgentUserBean item = lst.get(0);
        if (evt.getProfitRate() != null) {
            item.setProfitRate(evt.getProfitRate());
        }
        if (evt.getSubProfitRate() != null) {
            item.setSubProfitRate(evt.getSubProfitRate());
        }
        if (evt.getAgentLevel() != null) {
            item.setAgentLevel(evt.getAgentLevel());
            if (evt.getAgentLevel() == 1) {
                item.setCreateUser(999L);
                item.setParentGameId("-1");
            }
        }
        if (StringUtils.isNotBlank(evt.getUserName())) {
            item.setUserName(evt.getUserName());
        }
        baseRepository.save(item);
        return new ServiceResp().success("");
    }


    public ServiceResp bindBatch(BindAgentUserBatchEvt evt) {

        if (StringUtils.isBlank(evt.getSubUserIds())) return new ServiceResp().error("参数不能为空");
        String[] ids = StringUtils.split(evt.getSubUserIds(), ",");
        int i = 0;

        QueryAgentUserEvt queryAgentUserEvt = new QueryAgentUserEvt();
        queryAgentUserEvt.setGameId(evt.getSuperUserId());
        TAgentUserBean tAgentUserBean =
                agentUserMapper.queryByUserNo(queryAgentUserEvt);
        if (tAgentUserBean == null) return new ServiceResp().error("上级用户不存在");

        for (String item : ids) {
            // 查询记录是否存在
            QueryAgentUserEvt queryEvt = new QueryAgentUserEvt();
            queryEvt.setUserNo(item);
            List<TAgentUserBean> lst = query(queryEvt);
            if (lst == null || lst.size() == 0) continue;
            TAgentUserBean bean = lst.get(0);
            if (bean.getAgentLevel() != 3) continue;
            // 类型必须为玩家,绑定完后为二级代理
            bean.setParentGameId(evt.getSuperUserId());
            bean.setAgentLevel(2);
            bean.setProfitRate(tAgentUserBean.getSubProfitRate());
            bean.setAgentTime(new Date());
            baseRepository.save(bean);
            i++;
        }
        return new ServiceResp().success(i);
    }

    // 插入提现记录表
    @Transactional
    public synchronized ServiceResp doApplyWithDraw(DoApplyWithDrawEvt evt) {
        QueryAgentUserEvt queryEvt = new QueryAgentUserEvt();
        queryEvt.setUserNo(evt.getUserNo());
        List<TAgentUserBean> lst = query(queryEvt);
        if (lst == null || lst.size() == 0) return new ServiceResp().error("记录不存在");
        TAgentUserBean item = lst.get(0);
        // 判断额度是否满足提现  总分润金额-已提现金额>当前提现金额
        if (item.getProfitTotal() - item.getProfitUsedTotal() < evt.getAmount()) {
            return new ServiceResp().error("额度不够，无法发起提现");
        }
        // 插入提现记录
        TWithDrawBean tWithDrawBean = new TWithDrawBean();
        tWithDrawBean.setUserNo(item.getUserNo());
        tWithDrawBean.setAmount(evt.getAmount());
        tWithDrawBean.setAuditStatus("DSH");
        tWithDrawBean.setStatus(Status.E.name());
        tWithDrawBean.setCreateTime(new Date());
        tWithDrawBean = baseRepository.save(tWithDrawBean);
        // 冻结用户金额
        item.setProfitUsedTotal(item.getProfitUsedTotal() + evt.getAmount()); // 冻结金额累加上本次申请的金额
        baseRepository.save(item);
        tWithDrawBean.setGameId(evt.getGameId());
        return new ServiceResp().success(tWithDrawBean);
    }

}
